export async function onRequest({ request }) {

    const clientIp = request.eo.clientIp;
    //处理分割url
    const url = new URL(request.url);

    function createErrorResponse(status, message) {
        const ERROR_RESPONSE_HEADERS = {
            'Content-Type': 'text/html; charset=utf-8',
            'Access-Control-Allow-Origin': '*',
        };
        return new Response(
            `<html>
                <head>
                    <meta charset="utf-8"/>
                    <title>${message}${status}</title>
                </head>
                <body>${message}${status}</body>
            </html>`,
            { status, headers: ERROR_RESPONSE_HEADERS }
        );
    }

    async function verifyRequest() {
        const AuthURL = "https://auth.geek-talk.cn/api/authorize/authVerify";

        let token = url.searchParams.get('token');
        //token = "NzkzNjQwYmJmNzVmNTQ4ND"
        if (!token) {
            return false; // 验证失败
        }
        const data = {
            app_code: 'tarkov_api',
            ip: clientIp, // 替换为实际IP
            domain: 'www.domain.com', // 替换为实际域名
            auth_key: token // 替换为实际授权密钥
        };
        try {
            const authResponse = await fetch(AuthURL, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'server': '1'
                },
                body: JSON.stringify(data)
            }); if (!authResponse.ok) {
                throw new Error(`HTTP error! status: ${authResponse.status}`);
                return false; // 验证失败
            }

            const responseData = await authResponse.json();

            if (responseData.code === 1 && responseData.data?.status === 'success') {
                console.log("授权验证成功");
                return true;
            } else {
                console.log(`授权验证失败：${responseData.msg}`);
                return false;
            }
        } catch (error) {
            console.error(`请求错误：${error.message}`);
            return false;
        }

    }
    let verified = await verifyRequest()
    if (!verified) {
        return createErrorResponse(401, '验证未通过');
    }





    let resultJson = {};


    const tarkovDevURL = "https://api.tarkov.dev/graphql"
    let gameMode = 'regular'
    if (url.searchParams.get('gameMode') == 'pve') {
        gameMode = 'pve'
    }



    const tarkovDevoptions = {
        method: 'POST', // 请求方法  
        headers: { // 请求头  
            'Content-Type': 'application/json',
            'Accept': 'application/json',
        },
        body: JSON.stringify({ // 请求体  
            query: `{
                                    items(type: any,gameMode: ${gameMode})
                                    {
                                        id
                                        lastLowPrice
                                        avg24hPrice
                                        low24hPrice
                                        high24hPrice
                                    }
                                }`

        })
    };
    const [tarkovDevResponse, sptPriceResponse] = await Promise.all([
        fetch(tarkovDevURL, tarkovDevoptions),
        fetch("https://raw.githubusercontent.com/sp-tarkov/server/refs/heads/master/project/assets/database/templates/prices.json")
    ]);
    const tarkovDevJson = await tarkovDevResponse.json()
    const sptPriceJson = await sptPriceResponse.json()
    if (tarkovDevResponse.status !== 200) {

        return createErrorResponse(503, 'dev数据源暂不可用，请稍后重试');

    }


    if (sptPriceResponse.status !== 200) {

        return createErrorResponse(503, 'spt数据源暂不可用，请稍后重试');
    }


    async function handleTarkovDevResponse() {

        const tarkovDevJsonItems = tarkovDevJson.data.items

        const ResponseHandled = {};

        const priceMap = new Map(tarkovDevJsonItems.map(item => {
            const priceType = url.searchParams.get('pricetype') || 'avg24hPrice';
            return [item.id, item[priceType]];
        }));

        // 修改后的合并逻辑：仅当tarkov.dev有有效正数时才覆盖
        for (const id in sptPriceJson) {
            ResponseHandled[id] = 
                priceMap.has(id) && 
                priceMap.get(id) > 0 ?  // 过滤掉0和null
                priceMap.get(id) : 
                sptPriceJson[id];
        }
        return ResponseHandled;
    }
    let responseHandled = await handleTarkovDevResponse();



    switch (url.searchParams.get('type')) {
        case 'raw':
            resultJson = JSON.stringify(tarkovDevJson)
            break
        case 'MG':
            //处理日期时间
            const nowTime = new Date();
            let year = nowTime.getFullYear();
            let month = nowTime.getMonth();
            let day = nowTime.getDate();
            const mgDateArray = [year, month + 1, day]
            let mgFleaData = new Object
            mgFleaData["date"] = mgDateArray
            mgFleaData["prices"] = responseHandled

            resultJson = JSON.stringify(mgFleaData)
            break

        default:
            resultJson = JSON.stringify(responseHandled)
            break
    }



    return new Response(resultJson, {
        headers: {
            'content-type': 'application/json; charset=UTF-8',
            'Access-Control-Allow-Origin': '*',
        },
    });
}

const tarkovDevJsonExample =
{
    "data": {
        "items": [
            {
                "id": "5447a9cd4bdc2dbd208b4567",
                "lastLowPrice": 1000000,
                "avg24hPrice": null,
                "low24hPrice": null,
                "high24hPrice": null
            },
            {
                "id": "5447ac644bdc2d6c208b4567",
                "lastLowPrice": null,
                "avg24hPrice": null,
                "low24hPrice": null,
                "high24hPrice": null
            },
            {
                "id": "5448ba0b4bdc2d02308b456c",
                "lastLowPrice": 5555555,
                "avg24hPrice": null,
                "low24hPrice": null,
                "high24hPrice": null
            },
            {
                "id": "5448bd6b4bdc2dfc2f8b4569",
                "lastLowPrice": 11000,
                "avg24hPrice": null,
                "low24hPrice": null,
                "high24hPrice": null
            }
        ]
    }
}

const sptPriceJsonExample = {
    "5447a9cd4bdc2dbd208b4567": 88119,
    "5447ac644bdc2d6c208b4567": 14500,
    "5448ba0b4bdc2d02308b456c": 88911,
    "5448bd6b4bdc2dfc2f8b4569": 14132,
    "5448be9a4bdc2dfd2f8b456a": 13536,
    "5448c1d04bdc2dff2f8b4569": 5555,
    "5448fee04bdc2dbc018b4567": 13252,
    "5448ff904bdc2d6f028b456e": 14908
}